package cn.ixinjiu.libraryMangement.controller.admin.borrow;

import cn.ixinjiu.libraryMangement.dao.IBookInfoDao;
import cn.ixinjiu.libraryMangement.dao.IBorrowInfoDao;
import cn.ixinjiu.libraryMangement.dao.impl.BookInfoDaoImpl;
import cn.ixinjiu.libraryMangement.dao.impl.BorrowInfoDaoImpl;
import cn.ixinjiu.libraryMangement.entity.BookInfo;
import cn.ixinjiu.libraryMangement.entity.BorrowInfo;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by XinChen on 2023-06-26
 *
 * @TODO 归还图书： 1.修改借阅信息  2.修改图书状态
 */
@WebServlet("/adminBorrowInfoUpd")
public class BorrowInfoUpdServlet extends HttpServlet {
    private IBorrowInfoDao iBorrowInfoDao = new BorrowInfoDaoImpl();
    private IBookInfoDao iBookInfoDao = new BookInfoDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");
        // 获取前端参数
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        // 1.修改借阅信息
        BorrowInfo borrowInfo = iBorrowInfoDao.getBorrowInfoByBookId(bookId);
        Date date;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            date = sdf.parse(format);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        borrowInfo.setActualReturn(date);
        int borrowUpd = iBorrowInfoDao.borrowUpd(borrowInfo);
        // 2.修改图书状态
        BookInfo bookInfoById = iBookInfoDao.getBookInfoById(bookId);
        bookInfoById.setStatus(0);
        int update = iBookInfoDao.bookInfoUpd(bookInfoById);

        // 返回数据
        JSONObject json = new JSONObject();
        if (borrowUpd == 1 && update == 1) {
            json.put("code", "0");
            json.put("msg", "归还成功");
        } else {
            json.put("code", "1");
            json.put("msg", "归还失败");
        }
        // 输出到页面
        PrintWriter writer = resp.getWriter();
        writer.write(json.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
